/*
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-08-09 21:11:11
 * @LastEditTime: 2019-08-10 15:06:34
 * @LastEditors: Please set LastEditors
 */

//将get和post封装到一起
function ajax_tool(url, obj, method, success) {
    var s = urlEncode(obj);
    var data = s.slice(1);
    console.log(data);
    console.log(data);
    var ajax = new XMLHttpRequest();
    if (method == 'get') {
        if (data) {
            url += '?';
            url += data;
        } else {

        }
        ajax.open(method, url);
        ajax.send();
    } else if (method == 'post') {
        //post请求不需要改变
        ajax.open(method, url);
        // ajax.setRequestHeader("Content-type","x-www-form-urlencoded");
        ajax.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
        if (data) {
            ajax.send(data);
        } else {
            ajax.send();
        }
    }

    ajax.onreadystatechange = function () {
        if (ajax.readyState == 4 && ajax.status == 200) {
            console.log(ajax.responseText);
            //将数据让外边可以使用
            return ajax.responseText;
            // 当 onreadystatechange 调用时 说明 数据回来了
            // ajax.responseText;
            success(ajax.responseText);
        }
    }
}

function urlEncode(param, key, encode) {
    if (param == null) return '';
    var paramStr = '';
    var t = typeof (param);
    if (t == 'string' || t == 'number' || t == 'boolean') {
        paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
    } else {
        for (var i in param) {
            var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
            paramStr += urlEncode(param[i], k, encode)
        }
    }
    return paramStr;
    // return paramStr.substr(0,paramStr.length);

}
